package com.business.weixin.util;


import com.business.file.controller.gen.TFileController;
import com.business.util.Encrypt;
import com.business.util.HttpUtil;
import com.business.weixin.model.auto.WechatAccessToken;
import com.business.weixin.model.auto.WechatAccessTokenExample;
import com.business.weixin.service.WechatAccessTokenService;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.jeewx.api.core.exception.WexinReqException;
import org.jeewx.api.wxbase.wxtoken.JwTokenAPI;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WeixinService {

    public String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";

    @Autowired
    WechatAccessTokenService wechatAccessTokenService;

    /**
     * 获取accesstoken
     * @return
     */
    public String getAccessToken(){
        WechatAccessTokenExample example=new WechatAccessTokenExample();
        List<WechatAccessToken> list=wechatAccessTokenService.selectByExample(example);
        if(list!=null&&list.size()>0){
            WechatAccessToken token=list.get(0);
            return token.getAccessToken();
        }
        return null;
    }

    /**
     * 每个周期 更新一次accesstoken
     * @throws WexinReqException
     */
    public void updateAccessTokenPerHour(){
        try{
            String accessToken=JwTokenAPI.getAccessToken(Weixin.appId,Weixin.appSecret);
            WechatAccessTokenExample example=new WechatAccessTokenExample();
            List<WechatAccessToken> list=wechatAccessTokenService.selectByExample(example);
            WechatAccessToken at;
            if(list!=null&&list.size()>0){
                at=list.get(0);
                at.setAccessToken(accessToken);
                at.setUpdateTime(new Date());
                wechatAccessTokenService.updateByPrimaryKeySelective(at);
            }else{
                at=new WechatAccessToken();
                at.setAccessToken(accessToken);
                at.setUpdateTime(new Date());
                wechatAccessTokenService.insertSelective(at);
            }
        }catch (Exception e){

        }
    }

    /**
     * 根据code获取openid
     * @param code
     * @return
     * @throws Exception
     */
    public String getOpenidByCode(String code){
        try{
            String getCodeurl=url.replace("APPID", Weixin.appId).replace("SECRET", Weixin.appSecret).replace("CODE", code);
            String requestString=this.getRequest(getCodeurl);
            JSONObject jsonobject =JSONObject.fromObject(requestString);
            if(null!=jsonobject){
                String openid = jsonobject.getString("openid");
                if(!"".equals(openid)){
                    System.out.println("获取信息成功，openid:"+openid);
                    return openid;
                }else{
                    int errorrcode = jsonobject.getInt("errcode");
                    String errmsg = jsonobject.getString("errmsg");
                    System.out.println("错误码："+errorrcode+"————"+"错误信息："+errmsg);
                    return null;
                }
            }else{
                System.out.println("获取授权失败了，自己找原因。");
            }
        }catch(Exception e){
            return null;
        }
        return null;
    }

    public String getRequest(String urlString) throws Exception{
        URL urlToken = new URL(urlString);
        HttpURLConnection connToken = (HttpURLConnection)urlToken.openConnection();
        connToken.setDoOutput(true);
        connToken.setRequestMethod("POST");
        java.io.BufferedReader inToken = new java.io.BufferedReader(new java.io.InputStreamReader(connToken.getInputStream(),"UTF-8"));
        String lineToken;
        String tokenString="";
        while ((lineToken = inToken.readLine()) != null) {
            tokenString += lineToken;
        }
        inToken.close();
        //System.out.println(tokenString);
        return tokenString;
    }

    public String getTimestamp(){
        return Long.toString(System.currentTimeMillis() / 1000);
    }

    /**
     * 签名用的noncestr和timestamp必须与wx.config中的nonceStr和timestamp相同。
     * 签名用的url必须是调用JS接口页面的完整URL。
     *出于安全考虑，开发者必须在服务器端实现签名的逻辑。
     *
     */
    public String getSignature(String url,String timestamp,String noncestr){
        String jsapi_ticket=getJsapiTicket();
        String string1="jsapi_ticket="+jsapi_ticket+"&noncestr="+noncestr+"&timestamp="+timestamp+"&url="+url;
        String signature=new Encrypt().Encrypt(string1, "SHA-1");
        return signature;
    }

    /**
     * 获取jsapi_ticket
     * 根据access_token 采用http GET方式请求获得jsapi_ticket（有效期7200秒，开发者必须在自己的服务全局缓存jsapi_ticket）
     */
    public static String mediaUrl="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
    public String getJsapiTicket(){
        String access_token=getAccessToken();
        System.out.println("--开始从微信服务器获取jsapi_ticket--");
        String url="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+access_token+"&type=jsapi";
        System.out.println(url);
        JSONObject jo= HttpUtil.httpRequest(url,"GET","");
        return jo.get("ticket").toString();
    }

    public void downloadMedia(String mediaId){
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";
        String accessToken=this.getAccessToken();
        requestUrl = requestUrl.replace("ACCESS_TOKEN", this.getAccessToken()).replace(
                "MEDIA_ID", mediaId);
        HttpURLConnection conn = null;
        try {
            URL url = new URL(requestUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(30000);
            conn.setReadTimeout(30000);
            BufferedInputStream bis = new BufferedInputStream(
                    conn.getInputStream());
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = bis.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            byte[] filebyte = swapStream.toByteArray();
            File dir = new File(TFileController.uploadPath);
            if(!dir.exists()&&dir.isDirectory()){//判断文件目录是否存在
                dir.mkdirs();
            }
            FileCopyUtils.copy(filebyte,
                    new File(dir.getAbsolutePath() + "\\"
                            +  UUID.randomUUID()+".jpg"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(conn != null){
                conn.disconnect();
            }
        }
    }
}
